var express = require('express');
var router = express.Router();
var path = require('path');
var resultJson = require('../result-json');

var ossUtil = require('../utils/oss');

var fs = require('fs');
var multer  = require('multer')
var upload = multer({ 
    dest: path.resolve(__dirname, '../upload/'),
    limits: { fileSize: 5000000 }
})


var xlsx = require('node-xlsx');
 
function readXlsx(fileSrc){

    var list = xlsx.parse(fileSrc);
     
    // list.forEach(function(item){
    //     console.log(item['name']);
    //     // 读取每行内容
    //     for(var rowId in item['data']){
    //         console.log(rowId);
    //         var row=item['data'][rowId];
    //         console.log(row);
    //     }
    // });
    return list;
}


router.post('/upload.json', upload.single('file'), function(req, res, next){

    if (!req.file){
        res.end();
    }
    // 文件路径
    var filePath = req.file.path;  
    // 文件类型
    var temp = req.file.originalname.split('.');
    var fileType = temp[temp.length - 1];
    var lastName = '.' + fileType;
    // 构建图片名
    var fileName = Date.now() + lastName;

    // 图片重命名
    fs.rename(filePath, filePath + fileName, (err) => {

        if (err) {

            res.send(resultJson(5001));  
        }else{

            var localFile = filePath + fileName;  

            var jsonData = readXlsx(localFile);

            res.send(resultJson(0, jsonData));

            // 上传之后删除本地文件
            fs.unlinkSync(localFile);
        }
    });
})


module.exports = router;


